<template>
  <div class="TheTabbar">
    <el-tag class="tagStyle" size="default" v-for="(item, key) in list" :key="key" :closable="item.close" @close="handleClose(item)" @click="handleClick(item)" :type="item.type">{{
      item.name
    }}</el-tag>
  </div>
</template>

<script>
export default {
  data() {
    return {
      list: [
        {
          name: '首页',
          path: '/',
          type: '',
          close: false,
        },
      ],
      // 当前路由信息
      path: '',
    }
  },
  mounted() {
    // 获取当前路由信息
    this.path = this.$route.path
    this.setTabbar(this.$route)
  },
  methods: {
    // 点击跳转
    handleClick(item) {
      this.$router.push(item.path)
    },
    // 删除
    handleClose(item) {
      console.log(item)
      if (item.type == '') {
        // item.type == '' 表示删除的是当前路由
        // 删除当前路由后默认跳转到最后一个路由
        if (this.list.length > 1) {
          this.list.map((i, key) => {
            if (i.name == item.name) {
              this.list.splice(key, 1)
            }
          })
          this.$router.push(this.list[this.list.length - 1].path)
        }
      } else {
        // 直接删除
        this.list.map((i, key) => {
          if (i.name == item.name) {
            this.list.splice(key, 1)
          }
        })
      }
    },
    // 更改路由状态
    setTabbar(to) {
      // 路由发生变化,监测数组中是否存在当前路由信息
      let arr = {
        name: to.meta.pageTitle,
        path: to.path,
        type: 'info',
        close: true,
      }
      let isFlag = false // false  表示不存在
      this.list.map((item, key) => {
        if (to.meta.pageTitle == item.name) {
          isFlag = true
        }
      })
      // 根据 isFlag 判断是否需要push
      if (isFlag == false) {
        this.list.push(arr)
      }
      // 获取当前路由path
      let path = this.$route.path
      this.list.map((item, key) => {
        if (item.path == path) {
          item.type = ''
        } else {
          item.type = 'info'
        }
      })
    },
  },
  watch: {
    $route(to, from) {
      console.log('路由信息', this.$route)
      this.setTabbar(this.$route)
    },
  },
}
</script>
<style lang="scss" scoped>
.tagStyle {
  margin-right: 5px;
  margin-bottom: 5px;
  cursor: pointer;
}
</style>
